require 'Common/define'
require 'Logic/Config'
require 'Common/functions'

UICharactorPreviewWeapon = {};
HelperFunc.SetUIEnv(UICharactorPreviewWeapon)
local this = UICharactorPreviewWeapon;

this.gameObject = nil;
this.transform = nil;
this.LuaBehaviour = nil;

this.hasInit = false;

this.txtTitleName = nil;
this.btnReset = nil;
this.btnSkin = nil;
-- this.btnRefine;
-- this.btnInlay;
this.txtLevel = nil;
this.txtNextLevel = nil;
this.imgCostIcon = nil;
this.txtCostNum = nil;
-- this.txtAttrText1;
-- this.txtAttrText2;
-- this.btnAddLv;
this.btnAttribute = nil;
-- this.btnEquip;
this.btnSkill = nil;
this.btnClose = nil;

this.btnBefore = nil;
this.btnNext = nil;

this.objWeaponPos = nil;
this.objWeaponModel = nil;

this.weaponCfg = nil
this.weaponSkinConfig = nil;
this.weaponConfig = nil;
this.weaponAttrConfig = nil;
this.attributeConfig = nil
this.curHeroData = nil;
this.curWeaponData = nil;
this.allHero = nil;
this.nodeAttrRoot = nil
this.nodeAttrObj = nil
this.nodeAttrObjList = {}
this.callSwichFunc = nil;
this.icon = nil
this.iconCtrl = nil
this.desc1 = nil
---@type GList
this.attrList = nil
---@type GoWrapper
this.goWrapper = nil;
this.qualityPos = nil
this.UI_zhuanwu_front = nil
this.qualityObj = nil
this.qualityWraps = nil
function UICharactorPreviewWeapon.Init(data,callFunc,clollectList)--todo 应该小写 暂时先大写
    if attributeConfig == nil then
        attributeConfig = G.dataTable["t_attributelibrary"];
        weaponSkinConfig = G.dataTable["t_weaponshow"];
        weaponCfg = G.dataTable["t_weapon"]
    end

    allHero = clollectList--logicMgr.HeroManager.getOwnerHeroList(false);
    -- table.sort(allHero,logicMgr.HeroManager.sortHero);
    -- local myHero = logicMgr.HeroManager.getMyself();
    -- table.insert(allHero,1,myHero);

    this.callSwichFunc = callFunc;
    curHeroData = data--logicMgr.HeroManager.getHeroDatabyPartnerId(tostring(data));


    local name,package = getUIName(PanelResNames.UICharactorPreviewWeapon);
    panelMgr:ShowUI(name,package, this.onCreate, Config.useLocalUI);
end
---@param obj GComponent
function UICharactorPreviewWeapon.onCreate(obj)
    --gameObject = obj;
    --transform = obj.transform;

    if not hasInit then
        hasInit = true;
        txtTitleName = obj:GetChild("titleName")
        attrList = obj:GetChild("list")
        txtLevel = obj:GetChild("lv_number")

        objWeaponPos = obj:GetChild("ModelPos")
        txtNextLevel = obj:GetChild("nextLevel")
        this.btnBefore = obj:GetChild("before")
        this.btnNext = obj:GetChild("next")
        this.isShowOneController = obj:GetController("isShowOne")
        local tb = obj:GetChild("btnSkill")
        this.icon = tb:GetChild("Mask"):GetChild("Icon")
        this.iconCtrl = tb:GetController("improve")
        this.desc1 = obj:GetChild("skillDesc")
        this.qualityPos = obj:GetChild("Weapon_Grade_Front")
        this.UI_zhuanwu_front = obj:GetChild("UI_zhuanwu_front")
        goWrapper = GoWrapper.New()
        this.addEvent();
    end
    skillInfo =dataTable.getDataTable("t_weaponskill")[150000 + tonumber(curHeroData.partnerModelId)]
    this.UpSkill()
    this.FreshIcon()
    this.refresh();
    this.LoadEff()
end

function UICharactorPreviewWeapon.FreshIcon()
    icon.url = "ui://SkillAtlas/" .. G.dataTable["t_skillinfo"][tostring(skillInfo[20].f_WeaponSkill)].f_SkillIcon
    this.iconCtrl.selectedIndex = 3
end

function UICharactorPreviewWeapon.UpSkill()
    this.desc1.itemRenderer = this.ShowDec
    this.desc1.numItems = 1
end

function UICharactorPreviewWeapon.ShowDec(idx,obj)
    local config = skillInfo[60]
    local str = string.format(getLanguage("WeaponSkillText1"),config.f_WeaponLevel)..getLanguage(config.f_WeaponSkillDesc)
    obj:GetChild("DesText").text = str
end

function UICharactorPreviewWeapon.LoadEff()
    resMgr:LoadPrefab("UIEff/UI_zhuanwu_white", function(go)
        if qualityObj then
            destroy(qualityObj)
            qualityObj = nil
        end
        qualityObj = newObject(go);
        if not qualityWraps then
            qualityWraps = GoWrapper.New()
        end
        qualityObj:AddComponent(TCanvas);
        qualityWraps:SetWrapTarget(qualityObj, false)
        qualityPos:SetNativeObject(qualityWraps)
        Util.Lua_SetLocalPositionXYZ(qualityObj.transform,0, 0, 0);
    end);
end

function UICharactorPreviewWeapon.addEvent()
    this.btnBefore.onClick:Add(this.onClickBefore)
    this.btnNext.onClick:Add(this.onClickNext)
end

function UICharactorPreviewWeapon.removeEvent()
    this.btnBefore.onClick:Clear()
    this.btnNext.onClick:Clear()
end

function UICharactorPreviewWeapon.LocalListenEvent()
    ListenEvent(Config.EventType.Reset_Weapon,this.refresh);
    ListenEvent(Config.EventType.Update_Weapon,this.refresh);
    ListenEvent(Config.EventType.Update_WeaponAttrId,this.refresh);
end

function UICharactorPreviewWeapon.LocalCloseEvent()
    CloseEvent(Config.EventType.Reset_Weapon,this.refresh);
    CloseEvent(Config.EventType.Update_Weapon,this.refresh);
    CloseEvent(Config.EventType.Update_WeaponAttrId,this.refresh);
end

function UICharactorPreviewWeapon.OnDestroy()
    this.removeEvent();
    if qualityObj then
        destroy(qualityObj)
        qualityObj = nil
    end
    if qualityWraps then
        qualityWraps:Dispose()
        qualityWraps = nil
    end
end

function UICharactorPreviewWeapon.OnEnable()
    this.LocalListenEvent();
end

function UICharactorPreviewWeapon.OnDisable()
    this.LocalCloseEvent();
    if qualityObj then
        destroy(qualityObj)
        qualityObj = nil
    end
    if qualityWraps then
        qualityWraps:Dispose()
        qualityWraps = nil
    end
end


function UICharactorPreviewWeapon.refresh()
    this.isShowOneController.selectedIndex = #allHero > 1 and 0 or 1;
    local weaponID = 150000+ tonumber(curHeroData.partnerModelId)
    weaponConfig = G.dataTable["t_weapon"][tostring(weaponID)];
    txtTitleName.text = getLanguage(weaponConfig.f_WeaponName);
    local weaponAttrConfig = decodeJsonStrToTabel(weaponConfig.f_WeaponValue);
    local weaponInfo = weaponCfg[tostring(weaponID)]
    if not weaponInfo then return end
    --属性
    attrList:RemoveChildrenToPool()
    if weaponAttrConfig then
        local attribute = weaponAttrConfig[#weaponAttrConfig]
        for k,v in pairs(attribute) do
            local attrId = v[1]
            local attrNum = v[2]
            local attrSingle = attributeConfig[tostring(attrId)];
            --if attrSingle.f_IsPanel == 1 then
                local item = attrList:AddItemFromPool()
                local attrName = attrSingle.f_AttributeName;
                local attrNumStr= attrSingle.f_AttributeType ==1 and string.format("+%d",attrNum) or string.format("+%s%%",tostring(attrNum/100));
                local txtAttrValue = item:GetChild("txt_att_value")
                txtAttrValue.text = string.TextColor(attrNumStr,"#61B71B")
                local txtAttrName = item:GetChild("txt_att_name")
                txtAttrName.text = attrName
                local imgAttrIcon= item:GetChild("img_icon")
                imgAttrIcon.url = EnumConst.AtlasPath.ICONAtlas.."attr"..attrId
            --end
        end
    end

    --[[for k, v in pairs(attribute) do
        if nodeAttrObjList[k] then
            local oneObj = nodeAttrObjList[k]

            local attrId = v[1]
            local attrNum = v[2]
            local attrSingle = attributeConfig[tostring(attrId)];
            local attrName = attrSingle.f_AttributeName;
            local attrNumStr= attrSingle.f_AttributeType ==1 and string.format("+%d",attrNum) or string.format("+%s%%",tostring(attrNum/100));
            print(attrName..string.TextColor(attrNumStr,"#61B71B"))
            local txtAttrValue = oneObj.transform:Find("txt_att_value"):GetComponent("TextMeshProUGUI")
            txtAttrValue.text = string.TextColor(attrNumStr,"#61B71B")

            local txtAttrName = oneObj.transform:Find("txt_att_name"):GetComponent("TextMeshProUGUI")
            txtAttrName.text = attrName

            oneObj:SetActive(attrSingle.f_IsPanel == 1)

            resMgr:LoadIconFromPrefab("ICONAtlas","attr"..attrId,function (sp)
                local imgAttrIcon= oneObj.transform:Find("img_icon"):GetComponent("Image")
                imgAttrIcon.sprite = sp
            end)
        end
    end]]

    local list = decodeJsonStrToTabel(weaponInfo.f_WeaponShow)
    --品阶|皮肤
    if list then
        --local skinID = list[#list][2]
        --local level = list[#list][1]
        local skinID = list[1][2]
        local level = list[1][1]
        txtLevel.text = weaponInfo.f_MaxLevel
        txtNextLevel.text = string.format(getLanguage("Level"), weaponInfo.f_MaxLevel).."属性效果展示"
        local weaponSkin =weaponSkinConfig[tostring(skinID)];
        if weaponSkin~=nil then
            if objWeaponModel == nil or objWeaponModel.name~= weaponSkin.f_SpineID then
                
                resMgr:LoadPrefab("Model/Weapon/"..weaponSkin.f_SpineID,function (go)
                    if objWeaponModel~=nil then
                        destroyImmediate(objWeaponModel);
                        objWeaponModel = nil
                    end
                    objWeaponModel = newObject(go)
                    local x,y,z  = Util.Lua_GetLocalPositionXYZ(objWeaponModel.transform,0,0,0)
                    objWeaponModel:AddComponent(TCanvas)
                    goWrapper:SetWrapTarget(objWeaponModel,false)
                    objWeaponPos:SetNativeObject(goWrapper)
                    Util.Lua_SetLocalPositionXYZ(objWeaponModel.transform,x,y,z);
                end);
            end
        end
    end
    --end
end


function UICharactorPreviewWeapon.onClickReset()
    weaponHandler.sendWeaponResetMessage(curHeroData.partnerId);
end


function UICharactorPreviewWeapon.onClickSkin()  -- 皮肤
    showUI(PanelNames.UIWeaponSkin,curHeroData.partnerId);
end

function UICharactorPreviewWeapon.onClickAttribute()
    closeUI(PanelNames.UICharactorPreviewWeapon);
    showUI(PanelNames.UICharactorPreviewAttribute, curHeroData);
end

function UICharactorPreviewWeapon.onClickSkill()
    closeUI(PanelNames.UICharactorPreviewWeapon);
    showUI(PanelNames.UICharactorPreSkillview, curHeroData);
end

function UICharactorPreviewWeapon.onClickBefore()
    local index = 0;
    for i = 1, #allHero do
        if allHero[i]["partnerModelId"] == curHeroData["partnerModelId"]  then
            index =i;
            break;
        end
    end
    index = index -1;
    if index<1 then
        index = #allHero;
    end
    curHeroData = allHero[index];
    this.refresh();
    if this.callSwichFunc then
        this.callSwichFunc(true)
    end
end

function UICharactorPreviewWeapon.onClickNext()
    local index = 0;
    for i = 1, #allHero do
        if allHero[i]["partnerModelId"] == curHeroData["partnerModelId"]  then
            index =i;
            break;
        end
    end
    index = index +1;
    if index>#allHero then
        index = 1;
    end
    curHeroData = allHero[index];
    this.refresh();
    if this.callSwichFunc then
        this.callSwichFunc(false)
    end
end

function UICharactorPreviewWeapon.onClickClose()
    closeUI(PanelNames.UICharactorPreviewWeapon);
    -- if func~=nil then
    --     func();
    -- end
end

return UICharactorPreviewWeapon;
